package com.example.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
//import com.example.commons.tools.utils.AESUtils;
import com.example.utils.AESUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-30 22:53
 **/

/** 数据库中的数据类型 */
@MappedJdbcTypes(JdbcType.VARCHAR)
/** 处理后的数据类型 */
@MappedTypes(value = String.class)
public class AesTypeHandler extends BaseTypeHandler {
    private String decryptKey = "alexissbalexissb";
    private String decryptIv = "0120304050607080";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        if (ObjectUtil.isNotEmpty(parameter)){
            ps.setString(i, AESUtils.encrypt((String) parameter, decryptKey, decryptIv, AESUtils.AES_CBC));
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return StringUtils.isBlank(rs.getString(columnName)) ? rs.getString(columnName) : AESUtils.decrypt(rs.getString(columnName), decryptKey, decryptIv, AESUtils.AES_CBC);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
